<template>
  <component
    :is="tagName"
    :class="classes"
    v-bind="tagProps"
    @click="handleClickLink"
  >
    <!-- <div :class="headClasses" v-if="showHead"> -->
    <div :class="headClasses" v-if="$slots.title">
      <slot name="title">
        <p v-if="title">
          <Icon v-if="icon" :type="icon"></Icon>
          <span>{{ title }}</span>
        </p>
      </slot>
    </div>
    <!-- <div :class="extraClasses" v-if="showExtra"> -->
    <div :class="extraClasses" v-if="$slots.extra">
      <slot name="extra"></slot>
    </div>
    <div :class="bodyClasses" :style="bodyStyles">
      <slot></slot>
    </div>
  </component>
</template>
<script setup>
const prefixCls = 'haloe-card'
const defaultPadding = 16
import Icon from '../icon/icon.vue'
// import mixinsLink from '../../mixins/link'
import { oneOf } from '../../utils/assist'
import { ref, computed, useSlots,onMounted } from 'vue'
import {useLink} from './use-link'
const props = defineProps({
  bordered: {
    type: Boolean,
    default: true,
  },
  shadow: {
    type: String,
    validator(value) {
      return oneOf(value, ['hover', 'always', 'never'])
    },
    default: 'hover',
  },
  padding: {
    type: Number,
    default: defaultPadding,
  },
  title: {
    type: String,
  },
  icon: {
    type: String,
  },

  to: {
    type: [Object, String],
  },
  replace: {
    type: Boolean,
    default: false,
  },
  target: {
    type: String,
    validator(value) {
      return oneOf(value, ['_blank', '_self', '_parent', '_top'])
    },
    default: '_self',
  },
  append: {
    type: Boolean,
    required: false,
    default: false,
  },
})

let showHead = ref(true)
let showExtra = ref(true)

const slot=useSlots()

const {handleCheckClick,linkUrl}=useLink(props)

const classes = computed(() => {
  return [
    `${prefixCls}`,
    {
      [`${prefixCls}-bordered`]: props.bordered,
      [`${prefixCls}-${props.shadow}`]: props.shadow,
    },
  ]
})

const headClasses = computed(() => {
  return `${prefixCls}-head`
})

const extraClasses = computed(() => {
  return `${prefixCls}-extra`
})

const bodyClasses = computed(() => {
  return `${prefixCls}-body`
})

const bodyStyles = computed(() => {
  if (props.padding !== defaultPadding) {
    return {
      padding: `${props.padding}px`,
    }
  } else {
    return ''
  }
})
const isHrefPattern = computed(() => {
  return !!props.to
})

const tagName = computed(() => {
  return isHrefPattern.value ? 'a' : 'div'
})

const tagProps = computed(() => {
  if (isHrefPattern.value) {
    return { href: linkUrl.value, target: props.target }
  } else {
    return {}
  }
})

const handleClickLink = (event) => {
  if (!isHrefPattern.value) return
  const openInNewWindow = event.ctrlKey || event.metaKey
  handleCheckClick(event,openInNewWindow)
}

onMounted(() => {
  showHead.value=props.title|| slot.title!==undefined
  showExtra=props.extra!==undefined
})

</script>
